use std::collections::HashMap;

use super::http::{http_get, http_post};
use anyhow::{anyhow, Result};

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
pub struct EmptyObject {}

#[derive(Deserialize, Serialize)]
pub struct PagingRequest<T> {
    pub page_size: u32,

    pub page: u32,

    pub conditions: Option<T>,
}

#[derive(Deserialize, Serialize)]
pub struct PagingResponse<T> {
    pub page_size: u32,

    pub page: u32,

    pub total: u32,

    pub data: T,
}

const RRAI_BASE: &'static str = "https://www.idns.link/api";

pub async fn rrai_cloud_get(path: &String, token: &String) -> Result<String> {
    let mut headers = HashMap::new();
    headers.insert(String::from("Authorization"), token.clone());

    let (_, result) = http_get(&format!("{}{}", RRAI_BASE, path), &headers).await?;

    Ok(String::from_utf8(result).map_err(|err| anyhow!("{}", err))?)
}

pub async fn rrai_cloud_post(path: &String, token: &String, request_obj: String) -> Result<String> {
    let mut headers = HashMap::new();
    headers.insert(String::from("Authorization"), token.clone());
    headers.insert(
        String::from("Content-Type"),
        String::from("application/json"),
    );

    let (_, _, result) = http_post(
        &format!("{}{}", RRAI_BASE, path),
        &headers,
        request_obj.as_bytes().to_vec(),
    )
    .await?;

    Ok(String::from_utf8(result).map_err(|err| anyhow!("{}", err))?)
}

pub fn rrai_cloud_object_from_string<'a, T>(response: &'a String) -> anyhow::Result<T>
where
    T: Deserialize<'a>,
{
    serde_json::from_str(response.as_str()).map_err(|err| anyhow!("{}", err))
}
